﻿using System;
using Microsoft.Win32;

namespace HelloWorldBll
{
    public class SetAutoRun
    {
        /// <summary>
        /// 删除添加启动项
        /// </summary>
        /// <param name="keyName">启动项别名</param>
        /// <param name="filePath">程序路径</param>
        /// <returns></returns>
       public static bool DeteleAndSetAutoRun(string keyName, string filePath)
        {
            try
            {
                var hklm = Registry.LocalMachine;
                var software = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\", true);
                if (software != null)
                {
                    var aimdir = software.OpenSubKey("Run", true);
                    if (aimdir != null)
                    {
                        var aimnames = aimdir.GetValueNames();
                        foreach (var aimKey in aimnames)
                        {
                            if (aimKey == keyName)
                            {
                                aimdir.DeleteValue(keyName);
                            }
                        }
                    }
                    hklm.Close();
                }
                var runKey = hklm.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                if (runKey != null)
                {
                    runKey.SetValue(keyName, filePath);
                    runKey.Close();
                }
            }
            catch(Exception ex)
            {
                Log.log(ex.Message);
                return false;
            }
            return true;
        }
    }
}
